package br.com.simulador.session;

import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.framework.EntityQuery;

import br.com.simulador.model.Tag;

@Name("tagList")
public class TagList extends EntityQuery<Tag> {

	@In
	EntityManager entityManager;
	private static final String EJBQL = "select tag from Tag tag";

	private static final String[] RESTRICTIONS = { "lower(tag.descricao) like lower(concat(#{tagList.tag.descricao},'%'))", };

	private Tag tag = new Tag();

	public TagList() {
		setEjbql(EJBQL);
		setRestrictionExpressionStrings(Arrays.asList(RESTRICTIONS));
		setMaxResults(25);
	}

	public Tag getTag() {
		return tag;
	}
	
	public List<Tag> pesquisaTextual(String t){
		try{
			return (List<Tag>)entityManager.createQuery("select t from Tag t where t.descricao like :desc")
			.setParameter("desc", String.format("%%%s%%", t))
			.getResultList();
		}
		catch(NoResultException e){
			return null;
		}
		
	}
	
	public Tag pesquisaPorNome(String t){
		try{
			return (Tag) entityManager.createQuery("select t from Tag t where lower(t.descricao) = :desc")
			.setParameter("desc",  t.trim().toLowerCase())
			.getSingleResult();
		}
		catch(NoResultException e){
			return null;
		}
		
	}
	
	public void parseTags(String listTags, List<Tag> tags ){
		if(listTags != null){
			tags.clear();
			for(String t : listTags.split(",")){
				Tag tag = pesquisaPorNome(t.trim().toLowerCase());
				if(tag == null){
					tag = new Tag();
					tag.setDescricao(t.trim());
					entityManager.persist(tag);
					
				}
				tags.add(tag);

			}
		}
		
	}
	
	public String loadTags( List<Tag> tags){
		StringBuilder buffer = new StringBuilder();
		if(tags!=null ){
			
			for(Tag tag :tags){
				if(buffer.length()>0){
					buffer.append(",");
				}
				buffer.append(tag.getDescricao());
			}
			
		}
		return buffer.toString();
	}	
	
}
